package com.lyb.ui.controller;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import static com.lyb.constant.SystemConstant.SYSTEM_LOG_PATH;

/**
 * 日志页面的控制器
 *
 * @author Dayun Mr.Alpaca
 * @version 1.4.1
 */
public class LogController implements Initializable {
    @FXML
    private TextArea logDisplay;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        File logFile = new File(SYSTEM_LOG_PATH);
        if (!logFile.exists()) {
            jump();
        }

        /* 获取组件的动画 */
        KeyFrame logFrame = getLogFrame();

        /* 添加动画到时间线 */
        Timeline timeline = new Timeline();
        timeline.getKeyFrames().add(logFrame);
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.setAutoReverse(true);
        timeline.play();
    }

    /**
     * 获取日志组件的动画事件
     *
     * @return 动画
     */
    private KeyFrame getLogFrame() {
        return new KeyFrame(Duration.millis(1000), event -> {
            /* 若无日志文件则直接退出 */
            if (!new File(SYSTEM_LOG_PATH).exists()) {
                Stage stage = (Stage) logDisplay.getScene().getWindow();
                stage.close();
            }

            logDisplay.setText("");
            try (BufferedReader reader = new BufferedReader(new FileReader(new File(SYSTEM_LOG_PATH)))) {
                String str;
                while ((str = reader.readLine()) != null) {
                    logDisplay.appendText(str + "\n");
                }
            } catch (IOException ignored) { }
        });
    }

    /**
     * 若当前系统还未有日志文件则弹窗提示消息
     */
    private void jump() {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "", new ButtonType("取消", ButtonBar.ButtonData.NO),
                new ButtonType("确定", ButtonBar.ButtonData.YES));
        alert.setTitle("提示");
        alert.setHeaderText("当前系统日志文件内容为空");
        alert.showAndWait();
    }
}
